from django_redis import get_redis_connection
from rest_framework import serializers
import re

from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users.models import User, Address


class CreateUserSerializer(serializers.ModelSerializer):
    """定义一个注册用的序列化器 可以使用user的模型来创建"""
    password2 = serializers.CharField(label='确认密码', write_only=True)
    # redis中取出为字节类型解码为字符串后在验证
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token']

        # 添加格外的约束 验证username和password的长度
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名'
                }
            },
            'password': {
                'write_only': True,
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名'
                }
            }
        }

    # 校验手机号的格式
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    # 校验是否同意协议
    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    # 校验两次密码是否一致和短信验证码
    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']

        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        redis_conn = get_redis_connection('verify_codes')
        real_code = redis_conn.get("sms_%s" % mobile)
        if not real_code:
            raise serializers.ValidationError('无效的验证码')

        real_code = real_code.decode()
        if sms_code != real_code:
            raise serializers.ValidationError('验证码错误')

        return attrs

    def create(self, validated_data):
        # 删除数据库模型里面不存在的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # User.objects.create(**validated_data)
        user = super().create(validated_data)

        # 加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        self.context['request'].user = user

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email']

        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()
        verify_url = instance.generate_verify_email_url()
        to_email = instance.email
        send_verify_email.delay(to_email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='浏览商品信息', min_value=1)

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        else:
            return value

    def create(self, validated_data):
        # 把浏览历史添加进redis
        sku_id = validated_data.get('sku_id')
        user_id = self.context['request'].user.id

        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 去重 删除已经有的数据
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 把浏览历史添加进redis
        pl.lpush('history_%s' % user_id, sku_id)
        # 切片到只显示5条数据
        pl.ltrim('history_%s' % user_id, 0, 4)

        pl.execute()

        return validated_data


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']
